package ${package.domain}.service;

import ${package.common}.base.DomainResponse;
import ${package.domain}.entity.${entity};
import ${package.domain}.repository.I${entity}Repo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;

/**
 * ${table.comment!}领域服务
 *
 * @author ${author}
 * @since ${date}
 */
@Service
@AllArgsConstructor
public class ${entity}Service {

    /**
     * ${table.comment!}资源库
     */
    private final I${entity}Repo ${entity?uncap_first}Repo;

    /**
     * 创建${table.comment!}
     *
     * @param ${entity?uncap_first} ${table.comment!}实体
     * @return 响应结果
     */
    public DomainResponse<Void> create(@NotNull ${entity} ${entity?uncap_first}) {
        // 获取当前登录用户
        // SecurityUser securityUser = SecurityUserHelper.get();
        // 设置租户
        // ${entity?uncap_first}.setTenantId(securityUser.getTenantId());

        // 保存${table.comment!}
        ${entity?uncap_first}Repo.create(${entity?uncap_first});
        return DomainResponse.ok();
    }

    /**
     * 根据主键删除${table.comment!}
     *
     * @param ${entity?uncap_first}Id ${table.comment!}主键
     * @return 响应结果
     */
    public DomainResponse<Void> deleteById(@NotNull ${idPropertyType} ${entity?uncap_first}Id) {
        // 根据主键查询${table.comment!}
        ${entity} ${entity?uncap_first} = ${entity?uncap_first}Repo.queryById(${entity?uncap_first}Id);
        // ${table.comment!}数据存在且租户正确，删除${table.comment!}数据
        if (ObjectUtils.isNotEmpty(${entity?uncap_first}) && ${entity?uncap_first}.checkTenant()) {
            ${entity?uncap_first}Repo.deleteById(${entity?uncap_first}Id);
        }
        return DomainResponse.ok();
    }

    /**
     * 根据主键更新${table.comment!}
     *
     * @param ${entity?uncap_first} ${table.comment!}实体
     * @return 响应结果
     */
    public DomainResponse<Void> updateById(@NotNull ${entity} ${entity?uncap_first}) {
        // 根据主键查询${table.comment!}
        ${entity} exists = ${entity?uncap_first}Repo.queryById(${entity?uncap_first}.getId());
        // ${table.comment!}数据存在且租户正确，更新${table.comment!}数据
        if (ObjectUtils.isNotEmpty(exists) && exists.checkTenant()) {
            ${entity?uncap_first}Repo.updateById(${entity?uncap_first});
        }
        return DomainResponse.ok();
    }

    /**
     * 根据主键查询${table.comment!}
     *
     * @param ${entity?uncap_first}Id ${table.comment!}主键
     * @return 响应结果
     */
    public DomainResponse<${entity}> queryById(@NotNull ${idPropertyType} ${entity?uncap_first}Id) {
        ${entity} ${entity?uncap_first} = ${entity?uncap_first}Repo.queryById(${entity?uncap_first}Id);
        return DomainResponse.ok(${entity?uncap_first});
    }
}
